<?php
class Core_Utilities_Array {
	
	public function __construct() {
	
	}
	
	/**
	 * return array 
	 * 
	 * @param array $arrData
	 * @param int $parent
	 * @return array
	 */
	public function buildLevelArray($arrData, $parent = 0) {
		$arrResult = array();
		$this->recursive($arrData, $parent, 1, $arrResult);
		return $arrResult;
	}
	
	public function recursive($arrData, $parent = 1, $level = 1, &$arrResult) {
		if (sizeof($arrData)) {
			foreach ($arrData as $key => $item) {
				if ($item['parent_id'] == $parent) {
					$item['level'] = $level;
					$newParent = $item['id'];
					$arrResult[] = $item;
					unset($arrData[$key]);
					$this->recursive($arrData, $newParent, $level + 1, $arrResult);
				}
			}
		}
	}
	
	/**
	 * @param array $arrData
	 * @param int $newKey
	 * @return array
	 */
	public function buildArrayWithCustomKey($arrData, $newKey = 'id') {
		$arrResult = array();
		if (sizeof($arrData)) {
			foreach ($arrData as $key => $item) {
				if (isset($item[$newKey])) {
					$arrResult[$item[$newKey]] = $item;
				}
			}
		}
		return $arrResult;
	}
	
	/**
	 * @param array $arrData
	 * @param int $id
	 * @return array
	 */
	public function findChild($arrData, $id) {
		$arrResult = array();
		$this->recursiveFind($arrData, $id, $arrResult);
		return $arrResult;		
	}
	
	public function recursiveFind($arrData, $id, &$arrResult) {
		if (sizeof($arrData)) {
			$arrResult[] = $id;
			foreach ($arrData as $key => $item) {
				if ($item['parent_id'] == $id) {					
					$newId = $item['id'];										
					$this->recursiveFind($arrData, $newId, $arrResult);
				}
				unset($arrData[$key]);
			}
		}
	}
	
}